package com.gitee.j2cache.controller;

import com.gitee.j2cache.entity.User;
import com.gitee.j2cache.service.IUserService;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * UserController
 *
 * @Author: tedking
 * @Date: 2025-02-18
 */

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService ;


    @Autowired
    private CacheChannel cacheChannel;

     @GetMapping("/save")
    public Object save() {
        User user = new User() ;
        int num = new Random().nextInt(80);
        user.setAge(num) ;
        user.setName("姓名 - " + num) ;
        user.setSex(num >= 50 ? "男" : "女") ;
        return this.userService.save(user);
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable("id") Long id) {
        // 从指定的region，指定的key获取数据，如果一级，二级缓存中不存在，则通过第三个参数Function手动获取
        // 如果缓存中不存在时，同时配置了允许缓存空对象，则会缓存一个空对象到缓存中
        return this.cacheChannel.get("xj", id.toString(), key -> this.userService.get(id) , true) ;
    }

    @GetMapping("/delete/{id}")
    public Object remove(@PathVariable("id") Long id) {
        this.userService.delete(id) ;
        return "success";
    }
}
